/*!
 * New Launch.
 * Date: 2015/12/29.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
    'jquery',
		'pageInit',
		'formValidator',
    'formAjax',
    'notification',
    'flowplayer',
    'materialPreview',
    'holder',
    'uploadFiles'
	], function ($, vamakerPage, formValidator, formAjax, VamOpMsg, Flowplayer, MaterialPreview, holder, UploadFiles) {
  // New Creative Form.
  $(function () {
    var $dataFrm = $('#data-frm'),
      $imprMonitorFormCopy = $('.impr-monitor-url-new').detach().removeClass('hidden'),
      $clickMonitorFormCopy = $('.click-monitor-url-new').detach().removeClass('hidden'),
      $showMonitorUrl = $dataFrm.find('input[name="show_monitor_url"]'),
      $clickMonitorUrl = $dataFrm.find('input[name="click_monitor_url"]'),
      newMonitorUrl, delMonitorUrl, monitorUrlValidateCallback,
      $submitBtn = $dataFrm.find('button[type="submit"]'),
      dataFieldRule, options, dataValidator, newMaterialUrl, delMaterialUrl,
      $creativeTitle = $('#creative_title'),
      $creativeDescription = $('#creative_description'),
      $material = $('input[name="upload_material[]"]'),
      $uploadMaterial = $('#upload_material'),
      validateCallback, sizeValidateCallback, urlValidateCallback,
      $materialSource = $('#material_source').find('input[name="material_source"]'),
      $localMaterial = $('#local_upload_material'),
      $customUrl = $('#custom_material_url'),
      $materialUrl = $('.custom-url'),
      $adspaceWidth = $('.adspace-width'),
      $adspaceHeight = $('.adspace-height'),
      $materialFormCopy = $('.new-custom-url').detach().removeClass('hidden'),
      $feedsSubtypeWrapper = $('#feeds-sub-type-wrapper');
      
      //Select Material Source
      $materialSource.on('change', function(){
        var $me = $(this),
            meVal = $me.val();
        if (meVal === '1') {
          $customUrl.show();
          $localMaterial.hide();
        } else {
          $customUrl.hide();
          $localMaterial.show();
        };
        $('#creative_type').trigger('change');
      });
      $('input[name="material_source"]:checked').trigger('change');

      sizeValidateCallback = function (evt) {
        var $me = $(this),
        meVal = $me.val(),
        errorBox = $me.data('err'),
        $errorBox = $me.next('.'+errorBox),
        flag = true,
        msg = '';
        if (meVal === '') {
          flag = false;
          msg = VAM.j('Input cannot be empty!');
        } else if (!/^[0-9]*$/.test(meVal)) {
          flag = false;
          msg = VAM.j('Enter can only be integer!');
        } else if(parseInt(meVal,10) < 1) {
          flag = false;
          msg = VAM.j('Enter cannot be less than 1px!');
        };
        if (!flag) {
          msg = '<em class="checky-default-failure">' + msg + '</em>';
          $errorBox.html(msg);
        } else {
          $errorBox.html('');
        };
      };
      urlValidateCallback = function (evt) {
        var $me = $(this),
        meVal = $me.val(),
        errorBox = $me.data('err'),
        $errorBox = $me.next('.'+errorBox),
        creativeType = $('#creative_type').find('option:checked').val(),
        titleVal = $('#creative_title').val(),
        materialVal = $('#upload_material').val(),
        descriptionVal = $('#creative_description').val();
        strRegex = '^((https|http|ftp|rtsp|mms)?://)'
        flag = true,
        re = new RegExp(strRegex),
        msg = '';
        if (meVal === '' && creativeType !== '3') {
          flag = false;
          msg = VAM.j('Material url cannot be empty!');
        } else if (meVal === '' && creativeType === '3' && titleVal === '' && descriptionVal === ''){
          flag = false;
          msg = VAM.j('Creative title or description or material cannot be empty!');
        } else if (meVal !== '' && !re.test(meVal)){
          flag = false;
          msg = VAM.j('Please input the correct audit material Url (starting with http:// or https://)');
        };
        if (!flag) {
          msg = '<em class="checky-default-failure">' + msg + '</em>';
          $errorBox.html(msg);
        } else {
          $errorBox.html('');
        };
      };
    $materialUrl.on('blur', urlValidateCallback);
    $adspaceWidth.on('blur', sizeValidateCallback);
    $adspaceHeight.on('blur', sizeValidateCallback);
    newMonitorUrl = function($monitorFormNew, $monitorFormCopy){
      var len = $monitorFormNew.length;
      if (len < 5) {
        $monitorFormClone = $monitorFormCopy.clone(true);
        $monitorFormNew.last().after($monitorFormClone);
      }
    };
    delMonitorUrl = function(evt){
      evt.preventDefault();
      var $me = $(this),
          opRole = $me.data('type');
      $me.parents('.'+ opRole).remove();
    };
    monitorUrlValidateCallback = function(evt){
      var $me = $(this), 
          meVal = $me.val(), matchResult,
          $errBox = $me.next(),
          msg = VAM.j('Please input the correct monitor Url (starting with http:// or https://)');
          matchResult = /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/.test(meVal);
      if ($me.data('role') === 'click_url') {
        msg = VAM.j('Please input the correct monitor Url (starting with http:// or https://)');
      }
      if (meVal !== '' && !matchResult) {
        $errBox.html('<em class="checky-default-failure">' + VAM.j('Please input the correct monitor Url (starting with http:// or https://)') + '</em>');
      } else {
        $errBox.html('');
      }
    };

    $dataFrm.on('click', '.add-monitor-url', function(evt){
      evt.preventDefault();
      var $me = $(this),
          opType = $me.data('type');

      if (opType === 'impr-monitor-url') {
        newMonitorUrl($('.' + opType), $imprMonitorFormCopy);
      } else {
        newMonitorUrl($('.' + opType), $clickMonitorFormCopy)
      }
    });
    $dataFrm.on('click', '.del-url-operate', delMonitorUrl);
    $dataFrm.on('blur', 'input[name="show_monitor_url[]"]', monitorUrlValidateCallback);
    $dataFrm.on('blur', 'input[name="click_monitor_url[]"]', monitorUrlValidateCallback);

    $dataFrm.on('click', '.view-more-size', function (evt) {
      evt.preventDefault();
      var $me = $(this),
        meTxt = $me.text(),
        $sizeList = $me.siblings('.size-item:gt(10)');
      if (meTxt === VAM.j('More')) {
        $me.text(VAM.j('Fold'));
      } else {
        $me.text(VAM.j('More'));
      }
      $sizeList.toggleClass('vam-hidden');
    });

    // Add Material Url
    $dataFrm.on('click', '.add-material-url', function(evt){
      evt.preventDefault();
      var $materialFormNew = $('.custom-material-url'),
        len = $materialFormNew.length;
      if (len < 5) {
        $materialFormClone = $materialFormCopy.clone(true);
        $materialFormNew.last().after($materialFormClone);
      }
    });

    // Del Material Url
    $dataFrm.on('click', '.del-operate', function(evt){
      evt.preventDefault();
      var $me = $(this);
      $me.parents('.custom-material-url').remove();
    });

    // Feeds Material
    if ($material.length !== 0 ) {
      $uploadMaterial.val('1');
    };
    validateCallback = function (evt) {
      var $me = $(this),
      titleVal = $('#creative_title').val(),
      materialVal = $('#upload_material').val(),
      descriptionVal = $('#creative_description').val(),
      errorBox = $me.data('err'),
      $errorBox = $('#'+errorBox),
      $titleErrorBox = $('#creative_title_err'),
      $descriptionErrorBox = $('#creative_description_err'),
      $materialErrorBox = $('#upload_material_err'),
      $materialUrlErrorBox = $('#custom_material_url').find('.text-error'),
      creativeType = $('#creative_type').find('option:checked').val(),
      flag = true,
      msg = '';
      if (creativeType === '3' && titleVal === '' && descriptionVal === '' && materialVal === '') {
        flag = false;
        msg = VAM.j('Creative title or description or material cannot be empty!');
      };
      if (!flag) {
        msg = '<em class="checky-default-failure">' + msg + '</em>';
        $errorBox.html(msg);
      } else {
        $titleErrorBox.html('');
        $descriptionErrorBox.html('');
        $materialErrorBox.html('');
        $materialUrlErrorBox.html('');
      };
    };
  $creativeTitle.on('blur', validateCallback);
  $creativeDescription.on('blur', validateCallback);
  $uploadMaterial.on('blur', validateCallback);

  $('#creative_type').on('change', function(){
    var $required = $('.required').find('em');
      len = $required.length;
    if ($('#creative_type').val()!=='3') {
      if (!len) {
        $('.required').prepend('<em>*</em>');
      };
      $feedsSubtypeWrapper.addClass('vam-hidden');
    } else {
      $required.remove();
      $feedsSubtypeWrapper.removeClass('vam-hidden');
    };
    $('#upload_material_err').html('');
    $('#custom_material_url').find('.text-error').html('');
    $('#creative_title_err').html('');
    $('#creative_description_err').html('');
  });
  $('#creative_type').trigger('change');
    dataFieldRule = {
      creative_name:{
        rule:{
            required:{
                message:VAM.j('Creative cannot be empty')
            }
        },
        messageContainer:'creative_name_err'
      },
      landing_page_url:{
        rule:{
            required:{
                message:VAM.j('Target Url cannot be empty')
            },
            simpleUrl:{
              message:VAM.j('Please input the correct target Url (starting with http:// or https://)')
            }
        },
        messageContainer:'landing_page_url_err'
      },
      audit_target_url:{
        rule:{
            simpleUrl:{
              message:VAM.j('Please input the correct target Url (starting with http:// or https://)')
            }
        },
        messageContainer:'audit_target_url_err'
      },
    };
    options = {
      submitOnSucceed: false,
      onvalidate: function(evt) {
        if (evt.resultList.length <= 0) {
          var uploadMaterial = $('#upload_material').val(),
            materialUrl = $('.custom-url').val(),
            creativeDescription = $('#creative_description').val(),
            creativeTitle = $('#creative_title').val(),
            materialSourceVal = $('#material_source').find('input[name="material_source"]:checked').val(),
            creativeType = $('#creative_type').find('option:checked').val(),
            $materialUrl = $('.custom-url'),
            $adspaceWidth = $('.adspace-width'),
            $adspaceHeight = $('.adspace-height');
            if (materialSourceVal === '0') {
              if (creativeType!=='3') {
                var materialVal = $('#upload_material').val(),
                  $errorBox = $('#upload_material_err'),
                  flag = true,
                  msg = '';
                if (materialVal === '') {
                  flag = false;
                };
                if (!flag) {
                  msg = '<em class="checky-default-failure">' + VAM.j('Upload material cannot be empty') + '</em>';
                  $errorBox.html(msg);
                  return false;
                } else {
                  $errorBox.html('');
                };
                $creativeTitle.trigger('blur');
                $creativeDescription.trigger('blur');
                $uploadMaterial.trigger('blur');
              } else {
                if (uploadMaterial === '' && creativeDescription === '' && creativeTitle === '') {
                  $creativeTitle.trigger('blur');
                  $creativeDescription.trigger('blur');
                  $uploadMaterial.trigger('blur');
                  if ($('#creative_title_err').html() !== '' || $('#creative_description_err').html() !== '' || $('#upload_material_err').html() !== '') {
                    // evt.preventDefault();
                    event.preventDefault();
                    return false;
                  };
                };
              };
            } else {
              if (creativeType!=='3') {
                $materialUrl.trigger('blur', urlValidateCallback);
                $adspaceWidth.trigger('blur', sizeValidateCallback);
                $adspaceHeight.trigger('blur', sizeValidateCallback);
                var $inputErr = $('#custom_material_url').find('.text-error'),
                flag = 0;
                $inputErr.each(function(){
                  if (!!$(this).html()) {
                    flag += 1;
                  };
                });
                if (!!flag) {
                  return false;
                };
              } else {
                if (materialUrl === '' && creativeDescription === '' && creativeTitle === '') {
                  $creativeTitle.trigger('blur');
                  $creativeDescription.trigger('blur');
                  // $materialUrl.trigger('blur');
                  $('.custom-url-err').html('<em class="checky-default-failure">' + VAM.j('Creative title or description or material cannot be empty!') + '</em>');
                  if ($('#creative_title_err').html() !== '' || $('#creative_description_err').html() !== '' || $inputErr.html() !== '') {
                    // evt.preventDefault();
                    event.preventDefault();
                    return false;
                  }
                };
              };
            };
            $dataFrm.ajaxSubmit({
                beforeSubmit: function() {
                  $submitBtn.button('loading');
                },
                success: function (data) {
                  $submitBtn.button('reset');
                  if (data.status === 'success') {
                    VamOpMsg.messager(data);
                    if (VAM.getVar('CLOSE_DIALOG_FLAG') === true) {
                      $('.creative-preview-modal', window.parent.document).find('.btn-default').trigger('click');
                    } else {
                      window.location.href = 'creative-list';
                    }
                  } else {
                    VamOpMsg.messager(data);
                  }
                }
            });
        };
      }
    };
    formValidator.validate($dataFrm, dataFieldRule, options);
    dataValidator = formValidator.dataValidator;
    dataValidator.addRule('effectiveNumber',function(val, opt){
      return !!(val && /^\d+(\.\d{1,2})?$/.test(val));
    });
  });
  // Init Creative Upload.
  $(function () {
    var $uploadMaterial = $('#upload-material'),
      $uploadMaterialModal = $('#upload-material-modal'),
      $uploadMaterialInput = $('#upload_material'),
      $uploadMaterialOperate = $('#upload-confirm-operate'),
      $creativePreviewWrap = $('.creative-preview-wrap'),
      $creativeMaterialDefault = $('#creative_material_default'),
      videoPluginUrl = VAM.getVar('VIDEO_PLUGIN_URL');
    Flowplayer.conf = {
      swf: videoPluginUrl,
      muted: true,
      preload: 'metadata',
      tooltip: false,
      volume: 0.3
    };
    $uploadMaterialModal.on('hidden.bs.modal', function (evt) {
      var $me = $(this);
      $('#progress .progress-bar').css('width','0%').text('0%');
      $('#files').find('tbody').html('');
    });

    $uploadMaterial.on('click', function (evt) {
      var $me = $(this);
      $uploadMaterialModal.modal('show');
    });
    
    $uploadMaterialOperate.on('click', function(evt) {
      var $me = $(this),
        $uploadMaterialErr = $('#upload_material_err'),
        materialId = $me.data('materialId'),
        prevewInfo = $me.data('materialInfo');
      evt.preventDefault();
      // console.log(materialId);
      // console.log(prevewInfo);
      if (materialId !== '') {
        $uploadMaterialInput.val(materialId);
        $uploadMaterialModal.modal('hide');
        $uploadMaterialErr.html('');
        // TODO: creative material preview.
        MaterialPreview.previewMultiple($('.creative-preview-wrap'), prevewInfo, materialId);
        $('#upload_material').trigger('blur');
        $('.creative-preview-wrap').find('.flowplayer').flowplayer();
        $('#creative-preview-details').children().remove();
      } else {
        $uploadMaterialInput.val('');
      };
    });
    $creativePreviewWrap.on('click', '.preview-close', function(evt) {
      var $me = $(this),
        $parent = $me.parent();
      evt.preventDefault();

      $parent.fadeOut(function() {
        $parent.remove();
        if ($creativePreviewWrap.find('.creative-preview').length === 0) {
          if ($creativeMaterialDefault.hasClass('hidden')) {
            $creativeMaterialDefault.removeClass('hidden');
          } else {
            $creativeMaterialDefault.show();
          };
          $("#upload_material").val("");
        };
      });
    });
  });
  // Upload Creative Material.
  $(function () {
    'use strict';
    var url = VAM.getVar('UPLOAD_MATERIAL_URL'),
        $fileUpload = $('#fileupload'),
        $progressBar = $('#progress .progress-bar'),
        $table = $('#files').find('table tbody');
    $fileUpload.fileupload({
        url: url,
        dataType: 'json',
        done: function (e, data) {
          if (data.result.status === 'success') {
            var materialData = data.result.data,
             list = materialData['table'],
             listStr = '';
            // console.log(materialData);
            VamOpMsg.messager(data.result);
            listStr = '<tr>'
                    + '<td>' + materialData.id + '</td>'
                    + '<td>' + list.name + '</td>'
                    + '<td>' + list.size + '</td>'
                    + '<td>' + list.date + '</td>'
                    + '<td>' + list.judgeInfo + '</td>'
                    + '<td>' + list.updater + '</td>'
                    + '</tr>';
            $table.append(listStr);
            $('#upload-confirm-operate').data('materialId', materialData.id).data('materialInfo', materialData['preview']);
          }else {
            VamOpMsg.messager(data.result);
            $('#upload-confirm-operate').data('materialId', '');
          };
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $progressBar.css('width','0%').text('0%');
            $progressBar.css(
                'width',
                progress + '%'
            ).text(progress + '%');
        }
    })
    .prop('disabled', !$.support.fileInput)
    .parent().addClass($.support.fileInput ? undefined : 'disabled');
  });
  //Creative Vocation.
  $(function(){
    var creativeVocation = $.parseJSON(VAM.getVar('CREATIVE_VOCATION')),
      $vocationLarge = $('#creative_vocation_large'),
      $vocationSmall = $('#creative_vocation_small');
    for(var key in creativeVocation){
      if(creativeVocation.hasOwnProperty(key)) {
        $vocationLarge.append('<option value="'+key+'">' + key + '</option>');
      }
    }

    $vocationLarge.on('change',function(){
      var $me = $(this),
        vocationSmall = creativeVocation[$me.val()],
        i,j;
      $vocationSmall.children().remove();
      $vocationSmall.append('<option value="' + VAM.j('All') + '">' + VAM.j('All') + '</option>');
      for (i=0, j=vocationSmall.length; i<j; i++) {
        $vocationSmall.append('<option value="' + vocationSmall[i] + '">' + vocationSmall[i] +'</option>');
      }
    });

    var creativeParentVocation = VAM.getVar('parent_category');
    var creativeChildVocation = VAM.getVar('child_category');

    $("#creative_vocation_large option[value='"+creativeParentVocation+"']").attr('selected', "selected");
    $vocationLarge.trigger('change');
    $("#creative_vocation_small option[value='"+creativeChildVocation+"']").attr('selected', "selected");
  });
  // Video Creative Preview.
  $(function() {
    var videoPluginUrl = VAM.getVar('VIDEO_PLUGIN_URL'),
      $creativePreviewWrap = $('#creative-preview-details'),
      width = $('.creative-width').val(),
      height = $('.creative-height').val(),   
      type = $('.creative-type').val(),
      url = $('.creative-url').val(),
      info = {}, materialId = '';
    Flowplayer.conf = {
      swf: videoPluginUrl,
      engine: 'flash',
      muted: true,
      preload: 'auto',
      tooltip: false,
      volume: 0.3
    };
    info = {
      'width': width,
      'height': height,
      'type': type,
      'address': url
    };
    // console.log(info);
    MaterialPreview.previewMultiple($('.creative-preview-wrap'), info, materialId);
    $('.creative-preview-wrap').find('.flowplayer').flowplayer();
  });
});
